package com.example.securitymy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.securitymy.domain.ResponseResult;
import com.example.securitymy.domain.User;
import com.example.securitymy.domain.dto.ResetPasswordDto;
import com.example.securitymy.mapper.UserMapper;
import com.example.securitymy.service.PasswordResetService;
import com.example.securitymy.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class PasswordResetServiceImpl implements PasswordResetService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private VerificationCodeService verificationCodeService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public ResponseResult resetPassword(ResetPasswordDto resetPasswordDto) {
        // 验证验证码
        if (!verificationCodeService.verifyCode(resetPasswordDto.getEmail(), resetPasswordDto.getVerificationCode())) {
            return new ResponseResult(400, "验证码无效或已过期");
        }

        // 查找用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getEmail, resetPasswordDto.getEmail());
        User user = userMapper.selectOne(wrapper);

        if (user == null) {
            return new ResponseResult(404, "未找到该邮箱对应的用户");
        }

        // 更新密码
        user.setPassword(passwordEncoder.encode(resetPasswordDto.getNewPassword()));
        userMapper.updateById(user);

        return new ResponseResult(200, "密码重置成功");
    }
} 